package com.study.common.oAuth2;

import cn.hutool.core.convert.Convert;
import com.study.common.exception.ApiException;
import com.study.common.utils.JWTUtils;
import com.study.modules.sys.model.entity.SysUser;
import com.study.modules.sys.service.SysUserRoleService;
import com.study.modules.sys.service.SysUserService;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 自定义Realm
 *
 * @Author Mr.Du
 * @Date 2021/10/17 13:56
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysUserRoleService userRoleService;
    @Autowired
    private JWTUtils jwtUtils;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 执行授权逻辑
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权逻辑===》" + principalCollection);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取用户信息
        SysUser sysUser = (SysUser) principalCollection.getPrimaryPrincipal();
        //查询用户查询权限列表
        Set<String> perms = userRoleService.selectUserRole(sysUser.getId());
        info.addStringPermissions(perms);
        return info;
    }

    /**
     * 执行认证逻辑
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getCredentials();
        System.out.println("执行认证逻辑===》" + accessToken);
        Claims claims = jwtUtils.parseToken(accessToken);
        Long userId = 0L;
        if (claims == null || jwtUtils.isTokenExpired(claims.getExpiration())) {
            throw new IncorrectCredentialsException("token失效，请重新登录");
        } else {
            userId = Convert.toLong(claims.getSubject(), 0L);
            if (userId <= 0) throw new IncorrectCredentialsException("验签失败，登录签名不正确");
        }
        SysUser loginUser = userService.selectUserById(userId);
        if (loginUser == null) throw new ApiException("用户不存在！");
        if (loginUser.getDeleted().equals(1) || loginUser.getStatus().equals(1))
            throw new ApiException("用户被禁或被删除，请联系管理员！");
        return new SimpleAuthenticationInfo(loginUser, accessToken, getName());
    }
}
